<template>
  <div class="review-management">
    <div class="page-header">
      <h2>评论管理</h2>
      <button class="btn btn-default" @click="loadReviews">🔄 刷新</button>
    </div>

    <!-- 筛选条件 -->
    <div class="card filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>评分</label>
          <select v-model="filters.rating" @change="loadReviews">
            <option value="">全部</option>
            <option value="5">5星</option>
            <option value="4">4星</option>
            <option value="3">3星</option>
            <option value="2">2星</option>
            <option value="1">1星</option>
          </select>
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="filters.status" @change="loadReviews">
            <option value="">全部</option>
            <option value="1">显示</option>
            <option value="0">隐藏</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="card">
      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="reviews.length === 0" class="empty">
        暂无评论数据
      </div>

      <div v-else>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>商品名称</th>
              <th>用户</th>
              <th>评分</th>
              <th>评论内容</th>
              <th>回复数</th>
              <th>状态</th>
              <th>评论时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="review in reviews" :key="review.id">
              <td>{{ review.id }}</td>
              <td>{{ review.product_name || '-' }}</td>
              <td>
                <div class="user-info">
                  <div>{{ review.username || '用户' }}</div>
                  <div class="phone">{{ review.phone || '-' }}</div>
                </div>
              </td>
              <td>
                <div class="rating">
                  <span v-for="i in 5" :key="i" :class="i <= review.rating ? 'star-filled' : 'star-empty'">
                    ⭐
                  </span>
                </div>
              </td>
              <td>
                <div class="review-content">
                  {{ review.content }}
                  <div v-if="review.images && review.images.length > 0" class="review-images">
                    <img 
                      v-for="(img, idx) in review.images" 
                      :key="idx"
                      :src="img" 
                      alt="评论图片"
                      class="review-thumb"
                    />
                  </div>
                </div>
              </td>
              <td>{{ review.reply_count || 0 }}</td>
              <td>
                <span :class="['status-tag', review.status === 1 ? 'status-paid' : 'status-cancelled']">
                  {{ review.status === 1 ? '显示' : '隐藏' }}
                </span>
              </td>
              <td>{{ formatDate(review.created_at) }}</td>
              <td>
                <div class="actions">
                  <button class="btn btn-primary btn-sm" @click="showReplyModal(review)">
                    回复
                  </button>
                  <button 
                    class="btn btn-default btn-sm" 
                    @click="toggleStatus(review)"
                  >
                    {{ review.status === 1 ? '隐藏' : '显示' }}
                  </button>
                  <button class="btn btn-danger btn-sm" @click="deleteReview(review)">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页 -->
        <div class="pagination">
          <span>共 {{ total }} 条</span>
          <button @click="prevPage" :disabled="page <= 1">上一页</button>
          <span>第 {{ page }} 页</span>
          <button @click="nextPage" :disabled="page * pageSize >= total">下一页</button>
        </div>
      </div>
    </div>

    <!-- 回复弹窗 -->
    <div v-if="showReplyForm" class="modal" @click="closeReplyModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>回复评论</h3>
          <button class="close-btn" @click="closeReplyModal">✕</button>
        </div>
        <div class="modal-body">
          <!-- 评论信息 -->
          <div class="review-info">
            <div class="info-row">
              <strong>用户：</strong>{{ currentReview?.username || '用户' }}
            </div>
            <div class="info-row">
              <strong>评分：</strong>
              <span class="rating">
                <span v-for="i in 5" :key="i" :class="i <= currentReview?.rating ? 'star-filled' : 'star-empty'">
                  ⭐
                </span>
              </span>
            </div>
            <div class="info-row">
              <strong>内容：</strong>{{ currentReview?.content }}
            </div>
          </div>

          <!-- 已有回复 -->
          <div v-if="replies.length > 0" class="existing-replies">
            <h4>已有回复</h4>
            <div v-for="reply in replies" :key="reply.id" class="reply-item">
              <div class="reply-header">
                <span class="reply-author">
                  {{ reply.is_admin ? (reply.admin_name || '管理员') : (reply.username || '用户') }}
                </span>
                <span class="reply-time">{{ formatDate(reply.created_at) }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </div>
          </div>

          <!-- 回复表单 -->
          <div class="form-group">
            <label>管理员名称</label>
            <input v-model="replyFormData.admin_name" type="text" placeholder="如：客服小张" />
          </div>
          <div class="form-group">
            <label>回复内容 *</label>
            <textarea 
              v-model="replyFormData.content" 
              placeholder="请输入回复内容"
              rows="4"
            ></textarea>
          </div>
          <div class="form-actions">
            <button class="btn btn-default" @click="closeReplyModal">取消</button>
            <button class="btn btn-primary" @click="submitReply">提交回复</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getReviewsAdmin, getReviewReplies, replyReview, updateReviewStatus, deleteReview as deleteReviewApi } from '../api/review';

const reviews = ref([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const filters = ref({
  rating: '',
  status: ''
});

const showReplyForm = ref(false);
const currentReview = ref(null);
const replies = ref([]);
const replyFormData = ref({
  admin_name: '客服',
  content: ''
});

const loadReviews = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...filters.value
    };

    console.log('请求评论列表，参数:', params);
    const res = await getReviewsAdmin(params);
    console.log('评论列表响应:', res);
    
    if (res.success) {
      reviews.value = res.data.list || res.data || [];
      total.value = res.data.total || 0;
      console.log('评论数量:', reviews.value.length, '总数:', total.value);
    } else {
      alert(res.message || '加载失败');
      console.error('加载失败:', res);
    }
  } catch (error) {
    console.error('加载评论失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return dateStr.replace('T', ' ').substring(0, 19);
};

const showReplyModal = async (review) => {
  currentReview.value = review;
  showReplyForm.value = true;
  
  // 加载已有回复
  try {
    const res = await getReviewReplies(review.id);
    if (res.success) {
      replies.value = res.data || [];
    }
  } catch (error) {
    console.error('加载回复失败:', error);
  }
};

const closeReplyModal = () => {
  showReplyForm.value = false;
  currentReview.value = null;
  replies.value = [];
  replyFormData.value = {
    admin_name: '客服',
    content: ''
  };
};

const submitReply = async () => {
  if (!replyFormData.value.content) {
    alert('请输入回复内容');
    return;
  }

  try {
    const res = await replyReview(currentReview.value.id, replyFormData.value);
    if (res.success) {
      alert('回复成功');
      closeReplyModal();
      await loadReviews();
    } else {
      alert(res.message || '回复失败');
    }
  } catch (error) {
    console.error('回复失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

const toggleStatus = async (review) => {
  const newStatus = review.status === 1 ? 0 : 1;
  const action = newStatus === 1 ? '显示' : '隐藏';

  if (!confirm(`确定要${action}该评论吗？`)) return;

  try {
    const res = await updateReviewStatus(review.id, newStatus);
    if (res.success) {
      alert('操作成功');
      await loadReviews();
    } else {
      alert(res.message || '操作失败');
    }
  } catch (error) {
    console.error('更新状态失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

const deleteReview = async (review) => {
  if (!confirm(`确定要删除该评论吗？删除后无法恢复。`)) return;

  try {
    const res = await deleteReviewApi(review.id);
    if (res.success) {
      alert('删除成功');
      await loadReviews();
    } else {
      alert(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

const prevPage = () => {
  if (page.value > 1) {
    page.value--;
    loadReviews();
  }
};

const nextPage = () => {
  if (page.value * pageSize.value < total.value) {
    page.value++;
    loadReviews();
  }
};

onMounted(() => {
  loadReviews();
});
</script>

<style scoped>
.review-management {
  max-width: 100%;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: flex-end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  font-weight: 500;
}

.filter-item select {
  padding: 8px 12px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.phone {
  font-size: 12px;
  color: #999;
}

.rating {
  display: flex;
  gap: 2px;
}

.star-filled {
  color: #ffa500;
}

.star-empty {
  color: #ddd;
}

.review-content {
  max-width: 300px;
}

.review-images {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.review-thumb {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e5e5e5;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 20px;
  padding: 20px;
  border-top: 1px solid #e5e5e5;
}

.pagination button {
  padding: 6px 16px;
  border: 1px solid #e5e5e5;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination button:not(:disabled):hover {
  background: #f5f5f5;
}

.review-info {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-row {
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.existing-replies {
  margin-bottom: 20px;
}

.existing-replies h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
}

.reply-item {
  background: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 12px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reply-author {
  font-weight: 600;
  font-size: 14px;
  color: #1890ff;
}

.reply-time {
  font-size: 12px;
  color: #999;
}

.reply-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}
</style>

